import { ref } from 'vue';
import { defineStore } from 'pinia';
import { useRouter } from 'vue-router';
import { getRouterList } from '@/api/router';
import { listToTree } from '@/utils/menuTree';

export const useRouterStore = defineStore(
  'Router',
  () => {
    const router = useRouter();
    const isFirstRouter = ref(false);
    const routerList = ref([]);
    const routerTree = ref([]);

    //  获取路由
    const getRouterConfig = () => {
      return routerList.value;
    };

    const getRouter = async () => {
      const { success, data } = await getRouterList();
      if (success) {
        routerList.value = data;
        routerTree.value = listToTree(data);
      }
    };

    // 修改系统配置
    const changeFirstRouter = value => {
      isFirstRouter.value = value;
    };

    return {
      isFirstRouter,
      routerTree,
      routerList,
      getRouter,
      changeFirstRouter, //
      getRouterConfig,
    };
  },
  {
    persist: {
      key: id => `__persisted__${id}`,
      storage: sessionStorage,
      paths: ['routerTree', 'routerList'],
    },
  }
);
